<template>
  <div>
    <el-dialog
      ref="refDlg"
      :title="formData.id ? '编辑' : '新增'"
      :visible.sync="dialogShow"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="600"
      @close="handleBack"
    >
      <div>
        <el-form ref="refForm" class="financeForm" :rules="formRules" :model="formData" size="mini" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="限时分类:" size="mini" prop="timeLimitClass">
                <c-dict-select v-model="formData.timeLimitClass" dict-type-code="TIME_LIMIT_CLASS" placeholder="限时分类" style="width:100%" @change="changeTimeClass" />
              </el-form-item>
            </el-col>
            <el-col v-if="formData.timeLimitClass === 'PIC_DESIGN'" :span="12">
              <el-form-item label="门店建设范围:" size="mini" prop="constRange" :rules="[{ required: formData.timeLimitClass === 'PIC_DESIGN', message: '请选择门店建设范围' }]">
                <c-dict-select v-model="formData.constRange" dict-type-code="DECORATION_RANGE" placeholder="门店建设范围" style="width:100%" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="限时事项:" size="mini" prop="matter">
                <el-input v-model.trim="formData.matter" placeholder="请输入限时事项" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="限制时长（天）:" size="mini" prop="timeLimit">
                <el-input v-model.number="formData.timeLimit" placeholder="请输入限制时长（天）" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="formData.timeLimitClass === 'PIC_DESIGN'" :gutter="20">
            <el-col :span="12">
              <el-form-item label="业务类型:" size="mini" prop="bizType" :rules="[{ required: formData.timeLimitClass === 'PIC_DESIGN', message: '请选择业务类型' }]">
                <c-dict-select v-model="formData.bizType" dict-type-code="DESIGN_BIZ_TYPE" placeholder="业务类型" style="width:100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="修改时长（天）:" size="mini" prop="timeUpdate" :rules="[{ required: formData.timeLimitClass === 'PIC_DESIGN', message: '请输入修改时长（天）' }]">
                <el-input v-model.number="formData.timeUpdate" placeholder="请输入修改时长（天）" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="formData.timeLimitClass === 'PIC_DESIGN'" :gutter="20">
            <el-col :span="12">
              <el-form-item label="普通计算周期:" size="mini" prop="ordinaryCalculationArr" :rules="[{ required: formData.timeLimitClass === 'PIC_DESIGN', message: '请选择普通计算周期' }]">
                <c-dict-select v-model="formData.ordinaryCalculationArr" dict-type-code="CALCULATION_CYCLE" multiple placeholder="普通计算周期" style="width:100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="紧急计算周期:" size="mini" prop="urgentCalculationArr" :rules="[{ required: formData.timeLimitClass === 'PIC_DESIGN', message: '请选择紧急计算周期' }]">
                <c-dict-select v-model="formData.urgentCalculationArr" dict-type-code="CALCULATION_CYCLE" multiple placeholder="紧急计算周期" style="width:100%" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="formData.timeLimitClass === 'PIC_DESIGN'">
            <el-col>
              <el-form-item label="分配时间:" size="mini" prop="distributionTime" :rules="[{ required: formData.timeLimitClass === 'PIC_DESIGN', validator: validateT }]">
                <el-input v-model.number="formData.distributionTime" placeholder="请输入分配时间（小时）" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="formData.timeLimitClass !== 'PHASE_TRANSFER'" :gutter="20">
            <el-col :span="12">
              <el-form-item label="最小面积:" size="mini" prop="minArea" :rules="[{ required: formData.timeLimitClass === 'PIC_DESIGN', message: '请输入最小面积' }]">
                <el-input v-model.number="formData.minArea" placeholder="请输入最小面积" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="最大面积:" size="mini" prop="maxArea" :rules="[{ required: formData.timeLimitClass === 'PIC_DESIGN', message: '请输入最大面积' }]">
                <el-input v-model.number="formData.maxArea" placeholder="请输入最大面积" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="进度:" size="mini" prop="schedule">
                <el-input v-model="formData.schedule" placeholder="请输入进度" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer">
        <el-button size="mini" @click="handleBack">取消</el-button>
        <el-button type="primary" size="mini" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getDictByPatchType } from '@/api/dataDict'
import { saveTimeLimitRuls, getTimeLimitDetail } from '@/api/basicData'
// import { getUserInfo } from '@/utils/auth'
// import fileUploader from '@/components/importFile'
// import { postConfigAttachmentTemplate, changeFileList } from '@/api/proConfig'
// import { getShopAttachment } from '@/api/decorate'
export default {
  name: 'EidtDialog',
  // components: { fileUploader },
  props: {
    visible: {
      type: Boolean,
      default: false,
      required: true
    },
    detailData: {
      type: [String, Object],
      default: ''
    }
  },
  data() {
    const validateNum = (rule, value, callback) => {
      if (!value || value.length === 0) {
        return callback(new Error('请输入限时时长'))
      } else {
        if (isNaN(Number(value)) || Number(value) <= 0) {
          return callback(new Error('请输入正整数'))
        }
      }
      callback()
    }
    const validateArea = (rule, value, callback) => {
      if (value && (isNaN(Number(value)) || Number(value) <= 0)) {
        return callback(new Error('请输入正整数'))
      }
      callback()
    }
    const validateTime = (rule, value, callback) => {
      const reg = /^[1-9][0-9]?$/
      if (value && !reg.test(value)) {
        return callback(new Error('请输入数字不能以0开头，且不能大于24'))
      } else if (isNaN(Number(value)) || Number(value) <= 0 || value > 24) {
        return callback(new Error('请输入1到24的正整数'))
      } else if (value === '' || value === null || value === undefined) {
        console.log('value', value)
        return callback(new Error('请输入分配时间（小时）'))
      }
      callback()
    }
    return {
      flag: '',
      acceptTypeList: [],
      hasDuty: false,
      formData: {
        ordinaryCalculationArr: [],
        urgentCalculationArr: []
      },
      validateT: validateTime,
      formRules: {
        timeLimitClass: [{ required: true, message: '请选择限时分类' }],
        matter: [{ required: true, message: '请输入限时事项' }],
        timeLimit: [{ required: true, message: '请输入限时时长' },
          { validator: validateNum, message: '请输入正整数' }],
        maxArea: [{ validator: validateArea, message: '请输入正整数' }],
        minArea: [{ validator: validateArea, message: '请输入正整数' }]
      }
    }
  },
  computed: {
    dialogShow: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  created() {
    if (this.detailData.id) {
      getTimeLimitDetail(this.detailData.id).then(res => {
        if (res.success && res.data) {
          this.formData = res.data
          this.$set(this.formData, 'ordinaryCalculationArr', this.convertDataFormat(res.data.ordinaryCalculationCycle))
          this.$set(this.formData, 'urgentCalculationArr', this.convertDataFormat(res.data.urgentCalculationCycle))
        }
      })
    }
  },
  methods: {
    // 获取数据字典
    async getDictByPatchTypeAll(data) {
      const obj = await getDictByPatchType(data)
        .then(res => {
          return res
        })
      return obj
    },
    convertDataFormat(str) {
      if (!str || !str.length) return
      const arr = str.split(',')
      return arr
    },
    // 切换限时类型
    changeTimeClass(value) {
      if (value === 'PHASE_TRANSFER') {
        const { id, timeLimitClass, matter, timeLimit, schedule } = JSON.parse(JSON.stringify(this.formData))
        this.formData = { id, timeLimitClass, matter, timeLimit, schedule }
        this.formData.constRange = ''
        this.formData.bizType = ''
        this.formData.timeUpdate = ''
        this.$set(this.formData, 'ordinaryCalculationArr', [])
        this.$set(this.formData, 'urgentCalculationArr', [])
        this.formData.ordinaryCalculationCycle = ''
        this.formData.urgentCalculationCycle = ''
        this.formData.minArea = ''
        this.formData.maxArea = ''
        this.formData.distributionTime = ''
      } else if (value === 'OPERATION') {
        const { id, timeLimitClass, matter, timeLimit, maxArea, minArea, schedule } = JSON.parse(JSON.stringify(this.formData))
        this.formData = { id, timeLimitClass, matter, timeLimit, maxArea, minArea, schedule }
        this.formData.constRange = ''
        this.formData.bizType = ''
        this.formData.timeUpdate = ''
        this.$set(this.formData, 'ordinaryCalculationArr', [])
        this.$set(this.formData, 'urgentCalculationArr', [])
        this.formData.ordinaryCalculationCycle = ''
        this.formData.urgentCalculationCycle = ''
        this.formData.distributionTime = ''
      }
      this.$nextTick(() => {
        this.$refs.refForm.clearValidate()
      })
    },
    // 取消
    handleBack() {
      this.dialogShow = false
      this.clearForm()
    },
    // 清空表单
    clearForm(done) {
      this.formData = {
        staff: [],
        office: []
      }
      this.$refs.refForm && this.$refs.refForm.clearValidate()
      done && done()
    },
    // 提交
    submitForm() {
      this.$refs.refForm.validate((valid) => {
        if (valid) {
          if (Number(this.formData.maxArea) < Number(this.formData.minArea)) {
            this.$message.warning('最小面积不可大于最大面积，请重新输入')
            return
          }
          if (this.formData.timeLimitClass === 'PIC_DESIGN') {
            this.formData.ordinaryCalculationCycle = this.formData.ordinaryCalculationArr.toString()
            this.formData.urgentCalculationCycle = this.formData.urgentCalculationArr.toString()
          }
          saveTimeLimitRuls(this.formData).then(res => {
            if (res.success) {
              this.$message.success('操作成功')
              this.dialogShow = false
              this.clearForm()
              const isNew = !this.formData.id
              this.$emit('success', isNew)
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
